package com.caipos.akka;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 安全的Spring上下文持有类，确保获取Bean时上下文已初始化
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        // 仅在第一次设置或上下文不为空时更新
        if (applicationContext == null) {
            applicationContext = context;
        }
    }

    /**
     * 安全获取Bean，确保上下文已初始化
     */
    public static <T> T getBean(Class<T> beanClass) {
        if (applicationContext == null) {
            throw new IllegalStateException("Spring ApplicationContext is not initialized yet!");
        }
        return applicationContext.getBean(beanClass);
    }
}
    